<template>
  <a-modal class="common-modal" :title="title" :footer="null" :width="720" :visible="visible" @cancel="handleCancel" :maskClosable="false" style="top:5%;">
    <a-spin :spinning="confirmLoading">
      <a-form  class="common-modal-content pr-20">
        <div class="pb-20">
          <a-radio-group v-model:value="radioVal">
            <a-radio-button value="time">{{ $t('other.timeSegment') }}</a-radio-button>
            <a-radio-button value="style">{{ $t('other.byStyle') }}</a-radio-button>
          </a-radio-group> 
        </div>
        <div class="pr-20"> 
          <TimeTableForm v-show="radioVal == 'time'" :key="tableKey+1" ref="timeTableFormRef" :tableData="timeTableData" />
          <StyleTableForm v-show="radioVal == 'style'" :key="tableKey+2" ref="styleTableFormRef" :tableData="styleTableData"/>
        </div>
      </a-form>

      <div class="common-modal-footer">  
        <a-button @click="handleCancel" class="cancel">{{$t('common.cancel')}}</a-button>
        <a-button @click="handleOk" type="primary" class="confirm">{{$t('common.ok')}}</a-button> 
      </div>
    </a-spin>
  </a-modal>
</template>

<script setup>
import { ref } from 'vue' 
import TimeTableForm from './timeTableForm.vue'
import StyleTableForm from './styleTableForm.vue'
import axios from '@/utils/request'
import { message } from 'ant-design-vue'
import i18n from '@/locales/index'

const { t } = i18n.global
const emits = defineEmits(['ok'])
let title = ref('') 
let visible = ref(false)
let confirmLoading = ref(false)
let recordInfo = ref({}) 
let radioVal = ref()
let timeTableData = ref([]) // 时段表格
let styleTableData = ref([]) // 款式表格
const styleTableFormRef = ref()
const timeTableFormRef = ref()
let tableKey = ref(Math.random())
const edit = async (record) => { 
  title.value = `${record.lineNameAndNo}配置`
  tableKey.value = Math.random()
  let {lineName,lineNo,settingId} = record
  recordInfo.value = {lineName,lineNo,settingId}
  await getInfo(record.settingId)
  radioVal.value = 'time'
  visible.value = true
}
const getInfo = async (id) => {
  try {
    let res= await axios.postAction('/api/hanger/plan-production/get-setting', {planProductionSettingId: id})
    if(res.success)  {
      recordInfo.value.timeProductionItemDTOList = res.data.timeProductionItemDTOList || []
      recordInfo.value.styleProductionItemDTOList = res.data.styleProductionItemDTOList || []
      initTimeData(recordInfo.value.timeProductionItemDTOList)
      initStyleData(recordInfo.value.styleProductionItemDTOList)
    } 
  } catch {
    recordInfo.value.timeProductionItemDTOList = []
    recordInfo.value.styleProductionItemDTOList = []
    initTimeData()
    initStyleData()
  }
}
const initTimeData = (ary) => {
  if (!ary.length) {
    timeTableData.value = [{ timeRange: undefined, production: 0, id: Math.random() }]
  } else {
    timeTableData.value = ary.map(i => {
      return {
        production: i.production,
        timeRange: [timeChange(i.startTime), timeChange(i.endTime)],
        id: Math.random()
      }
    })
  }
}
const initStyleData = (ary) => { 
  styleTableData.value = !ary.length ? [{ styleNo: undefined, production: 0, id: Math.random() }] : ary.map(i => {
      return {
        styleNo: i.styleNo,
        production: i.production,
        id: Math.random()
      }
    })
} 
let timeChange = (time) => {
  let startAry = time.split(':')
  if (startAry.length == 3) startAry.pop()
  return startAry.join(':')
} 
const getParams = () => { 
  let {settingId, lineNo, lineName} = recordInfo.value
  let params = { 
    planProductionSettingId: settingId,
    lineNo,
    lineName
   }
  //  日期
  let timeData = timeTableFormRef.value.dataSource
  params.timeProductionItemDTOList = timeData.filter(i=> 
    i.timeRange?.length && (i.production || i.production ===0)
  ).map(i => {
    let { production, timeRange } = i
    return {
      endTime: timeRange[1],
      startTime: timeRange[0],
      production: production
    }
  })
  // 款式
  let styleData = styleTableFormRef.value.dataSource
  params.styleProductionItemDTOList = styleData.filter(i=> 
    i.styleNo && (i.production || i.production ===0)
  ).map(i => {
    let { production, styleNo } = i
    return { 
      production ,
      styleNo
    }
  }) 
  return params
}
const handleOk = async () => {
  try {
    let styleRes =  await styleTableFormRef.value.timeRef.validateFields() 
    let timeRes =  await timeTableFormRef.value.timeRef.validateFields() 
    if(!styleRes || !timeRes) message.warning('校验未通过，请修改后重试')
    confirmLoading.value = true
    let params = getParams() 
    const res = await axios.postAction('/api/hanger/plan-production/add-setting', params)
    if (res.success) {
      message.success(res.msg || t('common.doSuccess'))
      handleCancel()
      emits('ok')
    }
  } catch (err) {
    console.log('^^^^^^^^^^^^^^')
    confirmLoading.value = false
  }
}
const handleCancel = async() => {
  confirmLoading.value = false 
  timeTableData.value = []
  styleTableFormRef.value = []
  visible.value = false

}
defineExpose({
  edit
})
</script>
